//
//  PlayerViewController.m
//  海角音乐
//
//  Created by dllo on 15/8/12.
//  Copyright (c) 2015年 杨元石. All rights reserved.
//

#import "PlayerViewController.h"

@interface PlayerViewController () <AudioPlayerViewDelegate, STKAudioPlayerDelegate>

@end

@implementation PlayerViewController

- (void)dealloc
{

    [_Path release];
    [_dataArr release];
    [_reDetailModel release];
    [super dealloc];
}

+ (PlayerViewController *)shareHandleViewController
{
    static PlayerViewController *PlayVc = nil;
    
    if (PlayVc == nil) {
        
        PlayVc = [[PlayerViewController alloc] init];
    }
    return PlayVc;
}

// 页面刚进入时 判断歌曲状态, 如果是
- (void)viewWillAppear:(BOOL)animated
{
    // 根据 model 来为播放页面赋值
    ReDetailModel *model = [self.dataArr objectAtIndex:self.index];
    
    [audioPlayer getModel:model];    
    
    
    for (ReDetailModel *dataModel in [[DataBase shareDataBaseHandle] selectModel]) {
        
        if ([dataModel.singer_name isEqualToString:model.singer_name]) {
            
            self.isFlag = YES;
            
            [audioPlayer.likeButton setBackgroundImage:[UIImage imageNamed:@"红心.png"] forState:UIControlStateSelected];
            
            NSLog(@"已经收藏了");
            
        }else {
            
            self.isFlag = NO;
            
            [audioPlayer.likeButton setBackgroundImage:[UIImage imageNamed:@"空白.png"] forState:0];
            
            NSLog(@"还没有收藏那个");
        }
        
    }
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Player = [SinglePlayer shareHandleSinglePlayer];
    Player.delegate =self;
    audioPlayer = [[AudioPlayerView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) andAudioPlayer:Player];
    audioPlayer.delegate = self;
    [self.view addSubview:audioPlayer];
    [audioPlayer release];
    
    // 下一曲的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(PlayerTheMusic) name:@"PLAY" object:nil];
 
    
}
// 分享按钮
- (void)shareMusicButton
{

    

    
}
// 收藏按钮
- (void)collectMusic:(UIButton *)sender
{
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText;
    [HUD show:YES];
    [HUD hide:YES afterDelay:1];
    [self.view addSubview:HUD];
    
    sender.selected = !sender.selected;
    
    ReDetailModel *model = [self.dataArr objectAtIndex:self.index];
    
    if (sender.selected == NO) {
        
        [[DataBase shareDataBaseHandle] deleteModelInfo:model.number];
        
        [audioPlayer.likeButton setBackgroundImage:[UIImage imageNamed:@"空白.png"] forState:0];        
        HUD.labelText = @"取消收藏";
        
        
    } else {
        
        HUD.labelText = @"收藏成功";
        
        if ([[DataBase shareDataBaseHandle] selectModel].count == 0) {
            
            [[DataBase shareDataBaseHandle] createTable];
            
            [[DataBase shareDataBaseHandle] insertModelInfo:model];
            
            NSLog(@"daada    ==  %@", model.singer_name);
            
            [audioPlayer.likeButton setBackgroundImage:[UIImage imageNamed:@"红心.png"] forState:0];
            
        }
        _count = 0;
        for (ReDetailModel *mm in [[DataBase shareDataBaseHandle] selectModel]) {
            
            if (![mm.singer_name isEqualToString:model.singer_name]) {
                
                _count++;
                
                if ([[DataBase shareDataBaseHandle] selectModel].count == _count) {
                    
                    [[DataBase shareDataBaseHandle] insertModelInfo:model];
                    
                    [audioPlayer.likeButton setBackgroundImage:[UIImage imageNamed:@"红心.png"] forState:0];
                }
            }
        }
        
    }
    
   
    
}



// 下一曲
- (void)PlayerTheMusic
{
    [self nextButton];
}



// 页面消失
- (void)dismissViewController
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 改变模式
- (void)playWaysChange
{
    
    // 建立一个 MPB 显示切换信息
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText; // HUD 的文字模式
    [HUD show:YES];
    [HUD hide:YES afterDelay:1];  // 1秒后消失
    [self.view addSubview:HUD];
    
    if (self.playWays == PlayWithWayOneSongCirculation) {//单曲循环播放
        [audioPlayer.playWayButton setBackgroundImage:[UIImage imageNamed:@"suijibofang.png"] forState:UIControlStateNormal];
        self.playWays = PlayWithWayRandom;
        HUD.labelText = @"随机模式";
        return;
    }
    if (self.playWays == PlayWithWayRandom){//随机播放
        self.playWays = PlayWithWaySole;
        [audioPlayer.playWayButton setBackgroundImage:[UIImage imageNamed:@"ttpodicon-3.png"] forState:UIControlStateNormal];
        // Set custom view mode
        HUD.labelText = @"顺序播放";
        return;
    }
    else{//顺序循环
        self.playWays = PlayWithWayOneSongCirculation;
        [audioPlayer.playWayButton setBackgroundImage:[UIImage imageNamed:@"ttpodicon-2.png"] forState:UIControlStateNormal];
        // Set custom view mode
        HUD.labelText = @"单曲循环";        
        return;
    }
}


// 下一曲
- (void)nextButton
{
    
    if (self.playWays == PlayWithWaySole) {//如果为顺序循环播放
        
        if (self.index == [self.dataArr count]-1) {
            
            self.index = 0;
            // 显示
            HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            HUD.mode = MBProgressHUDModeText;
            [HUD show:YES];
            [HUD hide:YES afterDelay:1];
            [self.view addSubview:HUD];
            HUD.labelText = @"第一首歌曲";
            [self playtheMusic:self.index];
            return;
        }
        [self playtheMusic:++self.index];
    }
    if (self.playWays == PlayWithWayRandom){// 如果是随机
        
        self.index = arc4random() % self.dataArr.count;
        [self playtheMusic:self.index];
    }
    if (self.playWays == PlayWithWayOneSongCirculation){ // 如果是单曲循环模式
        [self playtheMusic:self.index];
    }
    
    
    
}

// 上一曲
- (void)preButton
{
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    HUD.mode = MBProgressHUDModeText;
    [HUD show:YES];
    [HUD hide:YES afterDelay:1];
    [self.view addSubview:HUD];
    
    if ([self.dataArr count]!=0) {
        self.index-=1;
        if (self.index<0) {
            self.index = 0;            
            HUD.labelText = @"第一首歌曲";
        }
        [self playtheMusic:self.index];
    }
}


// 歌曲的播放方法
- (void)playtheMusic:(NSInteger)index
{
    // 获取model 类 , 为单例 Bar 传值
    ReDetailModel * model = [self.dataArr objectAtIndex:index];
    BarPlayer = [DanLiPlayer shareHandleDanLiPlayer:CGRectZero];
    // model
    BarPlayer.reDetailModel = model;
    // 下标位置传出去 为了点进来获取下标
    BarPlayer.index = self.index;
    // 把播放模式传出去
    BarPlayer.playWays = self.playWays;
    // 改变标题
    [audioPlayer getModel:model];
    
// 判断数据
    // 两种数据
    if (model.singerName) {
        NSDictionary *dic = [model.auditionList objectAtIndex:1];
        NSString *url = [dic objectForKey:@"url"];
        [Player play:url];
    } else {
        NSDictionary *dic = [model.audition_list objectAtIndex:1];
        NSString *url = [dic objectForKey:@"url"];
        [Player play:url];
    }
}




//
#pragma mark - 播放器协议方法
/// Raised when an item has started playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didStartPlayingQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"开始播放");
}
/// Raised when an item has finished buffering (may or may not be the currently playing item)
/// This event may be raised multiple times for the same item if seek is invoked on the player
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishBufferingSourceWithQueueItemId:(NSObject*)queueItemId
{
    NSLog(@"完成加载");
}
/// Raised when the state of the player has changed
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer stateChanged:(STKAudioPlayerState)state previousState:(STKAudioPlayerState)previousState
{

}
/// Raised when an item has finished playing
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didFinishPlayingQueueItemId:(NSObject*)queueItemId withReason:(STKAudioPlayerStopReason)stopReason andProgress:(double)progress andDuration:(double)duration
{
    
//    
//    if (Player.state == STKAudioPlayerStateStopped) {
//        
//        NSNotificationCenter *play = [NSNotificationCenter defaultCenter];
//        [play postNotificationName:@"PLAY" object:nil];
//    }
    
    
    
    NSLog(@"结束播放");
}
/// Raised when an unexpected and possibly unrecoverable error has occured (usually best to recreate the STKAudioPlauyer)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer unexpectedError:(STKAudioPlayerErrorCode)errorCode
{

}


/// Optionally implemented to get logging information from the STKAudioPlayer (used internally for debugging)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer logInfo:(NSString*)line
{

}
/// Raised when items queued items are cleared (usually because of a call to play, setDataSource or stop)
-(void) audioPlayer:(STKAudioPlayer*)audioPlayer didCancelQueuedItems:(NSArray*)queuedItems
{

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
